<?php

namespace app\admin\model\yunfood;

/**
 * 轮播图
 */
class Slide extends \addons\yunfood\model\Slide
{
    // 自定义初始化
    protected static function init()
    {
        self::beforeWrite(function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario) {
                $redirectData = [];
                if ($record['redirect_type'] == self::REDIRECT_TYPE_LINK) {
                    $redirectData = $record->data['linkData'];
                } elseif ($record['redirect_type'] == self::REDIRECT_TYPE_PAGE) {
                    $redirectData = $record->data['pageData'];
                } elseif ($record['redirect_type'] == self::REDIRECT_TYPE_SOURCE) {
                    $redirectData = $record->data['sourceData'];
                }
                $record->redirect_data = json_encode($redirectData);

                unset($record->data['scenario']);  // 避免afterInsert的操作
            }

            return true;
        });

        self::afterInsert(function ($row) {
            $row->save(['weigh' => $row['id']]);
        });
    }

    // 图片 - 覆盖父类
    public function getImageUrlAttr($value, $data)
    {
        return $value;
    }
}
